package com.yn.xgame.logic;

import com.google.common.collect.ImmutableMap;
import com.yn.xgame.*;
import com.yn.xgame.game.GameCenterWatcher;
import com.yn.xgame.game.fish.GCFishEnterTable;
import com.yn.xgame.game.message.CommonGameStartNotice;
import com.yn.xgame.game.message.GameGoldChanged;
import com.yn.xgame.game.message.PlayerLeave;
import com.yn.xgame.logic.handler.ShuiHuHandler;
import com.yn.xgame.logic.handler.ShuiHuHandler.Result;
import com.yn.xgame.logic.util.CheckUtils;
import com.yn.xgame.message.C2GPbRedirectMessage;
import com.yn.xgame.message.MqBeanMessage;
import com.yn.xgame.message.UserSessionMessage;
import com.yn.xgame.pb.FishProto;
import com.yn.xgame.pb.GateClientProto;
import com.yn.xgame.pb.MessageIdProto;
import com.yn.xgame.pb.MessageIdProto.MessageId;
import com.yn.xgame.po.LoadInfo;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * LogicServer Created by wangboo on 17/7/13.
 */
public class LogicServer extends ThreadServer implements IFuncServerLike {

    private static final Logger logger = LoggerFactory.getLogger(LogicServer.class);
    private GamePlayerManager playerManager;
    final LoadInfo loadInfo;
    GameCenterWatcher gameCenterWatcher;
    private String topic;
    private Set<Long> dumpTimerSet;

    public LogicServer() {
        super("Logic" + LogicApp.config.getId());
        playerManager = new GamePlayerManager();
        // int id, String ip, int port, String topic, int cur, int max, int
        // state
        topic = LogicApp.config.getTopic();
        loadInfo = new LoadInfo(LogicApp.config.getId(), LogicApp.config.getInnerIp(), LogicApp.config.getPort(),
                LogicApp.config.getTopic(), 0, LogicApp.config.getMaxUser(), LoadInfo.STATE_WORKING);
        useTimerManager();
        dumpTimerSet = new HashSet<>();
        getTimerManager().tickForever(10_000, 10_000, this::updateToZK);
    }

    private void updateToZK() {
        if (loadInfo.cur == playerManager.size())
            return;
        LogicApp.zkClient.createOrsetData_EPHEMERAL("/logic/" + loadInfo.id, loadInfo);
    }

    @Override
    public boolean handleMessage(IMessage message) {
        if (super.handleMessage(message)) {
            return true;
        } else if (message instanceof C2GPbRedirectMessage) {
            handleC2GMessage((C2GPbRedirectMessage) message);
            return true;
        } else if (message instanceof MqBeanMessage) {
            handleMqBeanMessage((MqBeanMessage) message);
            return true;
        }
        return false;
    }

    private void handleMqBeanMessage(MqBeanMessage msg) {
        switch (msg.getMsgId()) {
            case MqMsgId.gate_user_disconnect:
                handleUserDisconnect((Map<String, Object>) msg.getBean());
                break;
            case MqMsgId.common_player_game_start_notice:
                handleEnterRoomResp(msg);
                break;
            case MqMsgId.g2l_player_gold_changed:
                handlePlayerGoldChanged((GameGoldChanged) msg.getBean());
                break;

        }
    }

    private void handleUserDisconnect(Map<String, Object> msg) {
        long sid = (long) msg.get("sid");
        GamePlayer player = playerManager.getPlayerBySessionId(sid);
        if (player != null) {
            player.setLastLeaveTime(System.currentTimeMillis());
            long dumpTimer = getTimerManager().tickOnce(GlobalSetting.TIME_DUMP_SECONDS, player::dumpToDB);
            dumpTimerSet.add(dumpTimer);
            // 正在进行的游戏，通知后续服务器，玩家掉线
            if (player.getCenterTopic() != null) {
                PlayerLeave leave = new PlayerLeave();
                leave.userId = player.getUserId();
                leave.center = player.getCenterTopic();
                leave.game = player.getGame();
                leave.roomId = player.getRoomId();
                leave.sessionId = player.getSessionId();
                leave.tableId = player.getTableId();
                LogicApp.mqClient.sendInter(topic, player.getCenterTopic(), MqMsgId.common_player_leave, leave);
                if (player.getGameTopic() != null) {
                    LogicApp.mqClient.sendInter(topic, player.getGameTopic(), MqMsgId.common_player_leave, leave);
                }
            }
        }
    }

    private void handlePlayerGoldChanged(GameGoldChanged bean) {
        GamePlayer player = playerManager.getPlayer(bean.uid);
        if (player == null) {
            logger.warn("player sid: {} not found", bean.uid);
            return;
        }
        player.setUserWalletGold(Long.toString(bean.gold));
    }

    // 客户端请求
    private void handleC2GMessage(C2GPbRedirectMessage msg) {
        switch (msg.getPb().getMsgid()) {
            case C2G_Login:
                // 登陆请求
                handleLogin(msg);
                break;
            case C2G_Regist:
                handleRegist(msg);
                break;
            case C2G_BackPack:// 背包
                handleQueryBackPack(msg);
                break;
            case C2G_UserMsg:// 信息
                handleQueryMsg(msg);
                break;
            case C2G_DeleteUserMsg://删除信息
                deletUserMsg(msg);
                break;
            case C2G_ReadMsgReq://已读信息
            	handleReadMsg(msg);
            	break;
            case C2G_UserBankAssetsLog://存取款记录
                handleBankAssetsLog(msg);
                break;
            case C2G_AddOrLoginUserBank://添加银行密码
                addOrLoginUserBank(msg);
                break;
                
            case C2G_DrawMoney://取款
                handleDrawMoney(msg);
                break;
            case C2G_DepositMoney://存款
                handleWithDepositMoney(msg);
                break;
            case C2G_UpdateUserBankPwd://修改银行密码
                updateUserBankPwd(msg);
                break;
            case C2G_ChangeUserBaseInfoReq://修改个人信息
                handleUserBaseInfo(msg);
                break;
            case C2G_CaptchaReq: //验证码
                handleCaptcha(msg);
                break;
            case C2G_GameCenterInfoQuery:
                handleGameCenterInfoQuery(msg);
                break;
//            case C2G_GCEnter:   // 暂时废弃，各个游戏分开处理
//                handleEnterRoom(msg);
//                break;
            case C2G_GCEnterFishTable:
                handleFishEnterTable(msg);
                break;
            case C2G_FishCreate:
            case C2G_FishDeath:
            case C2G_FishBullet:
                // 全部重定向到游戏服
                handleRedirectToGameServer(msg);
                break;
            case C2G_FishPlayerLeave:
                // 重定向到游戏服和game center
                handleRedirectToGameServer(msg);
                handleRedirectToGCServer(msg);
                break;
            case C2G_ShuiHuBeginReq:
            	handleShuiHuBeginReq(msg);
            	break;
            case C2G_SHMaliReq:
            	handleSHMaliReq(msg);
            	break;
            case C2G_SHBiBeiReq:
            	handleSHBiBeiReq(msg);
            	break;
        }

    }
    //已读信息
    private void handleReadMsg(C2GPbRedirectMessage msg) {
    	 GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
         XAssert.nonNull(player, msg);
         player.getUserMessageModule().handleReadMsg(msg);
		
	}

	// 水浒
    private void handleShuiHuBeginReq(C2GPbRedirectMessage msg){
    	GateClientProto.G2CMessage.Builder g2cb=GateClientProto.G2CMessage.newBuilder();
    	Pair<Integer,Result> pair=ShuiHuHandler.begin(msg, playerManager);
    	switch(pair.getKey()){
    	case 1:
    		GateClientProto.ShuiHuEndResp.Builder shb=GateClientProto.ShuiHuEndResp.newBuilder();
    		shb.setPatterns(pair.getValue().getYwpArrstr());
    		shb.setBalance(pair.getValue().getBalance());
    		shb.setMltimes(pair.getValue().getMltimes());
    		shb.setSpecial(pair.getValue().getSpecial());
    		g2cb.setShuiHuEndResp(shb.build());
    		break;
    	case 2:
    		g2cb.setResult(2).setWarning("游戏筹码不足，请前往充值");
    		break;
    	case 3:
    		g2cb.setResult(3).setWarning("请登录...");
    		break;
    	case 4:
    		g2cb.setResult(4).setWarning("错误的请求");
    		break;
    	case 5:
    		g2cb.setResult(5).setWarning("ERROR");
    	}
    	respToClient(msg, g2cb.setMsgid(MessageId.G2C_ShuiHuEndResp).build());
    }
    // 水浒玛丽
    private void handleSHMaliReq(C2GPbRedirectMessage msg) {
    	Pair<Integer,Result> pair=ShuiHuHandler.mali(msg, playerManager);
    	GateClientProto.G2CMessage.Builder g2cb=GateClientProto.G2CMessage.newBuilder();
    	switch(pair.getKey()){
    	case 1:
    		GateClientProto.SHMaliResp.Builder shmb=GateClientProto.SHMaliResp.newBuilder();
    		shmb.setPatterns(pair.getValue().getYwpArrstr()).setBalance(pair.getValue().getBalance()).setMltimes(pair.getValue().getMltimes());
    		g2cb.setShMaliResp(shmb.build());
    		break;
    	case 3:
    		g2cb.setResult(3).setWarning("请登录");
    		break;
    	case 4:
    		g2cb.setResult(4).setWarning("错误的请求");
    	}
    	respToClient(msg, g2cb.setMsgid(MessageId.G2C_SHMaliResp).build());
    }
    
   
    // 水浒比倍
    private void handleSHBiBeiReq(C2GPbRedirectMessage msg) {
    	Pair<Integer,Result> pair=ShuiHuHandler.bibei(msg, playerManager);
    	GateClientProto.G2CMessage.Builder g2cb=GateClientProto.G2CMessage.newBuilder();
    	switch(pair.getKey()){
    	case 1:
    		GateClientProto.SHBiBeiResp.Builder shbb=GateClientProto.SHBiBeiResp.newBuilder();
    		shbb.setDices(pair.getValue().getYwpArrstr()).setBalance(pair.getValue().getBalance());
    		g2cb.setShBiBeiResp(shbb.build());
    		break;
    	case 3:
    		g2cb.setResult(3).setWarning("请登录");
    		break;
    	case 4:
    		g2cb.setResult(4).setWarning("错误的请求");
    	}
    	respToClient(msg, g2cb.setMsgid(MessageId.G2C_SHBiBeiResp).build());
    }

    private void handleRedirectToGCServer(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        if (player != null && player.getCenterTopic() != null) {
            // 从定向到gc服
            LogicApp.mqClient.sendPbRedirect(player.getCenterTopic(), msg);
        }
    }

    private void handleRedirectToGameServer(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        if (player != null && player.getGameTopic() != null) {
            // 从定向到游戏服
            LogicApp.mqClient.sendPbRedirect(player.getGameTopic(), msg);
        }
    }

    private void handleFishEnterTable(C2GPbRedirectMessage msg) {
        FishProto.FishEnterTable req = msg.getPb().getFishEnterTable();
        int type = req.getRid();    // 房间id 1十炮场，2百炮场。。。。
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg.getSessionId());
        GCFishEnterTable gc = new GCFishEnterTable();
        gc.type = type;
        gc.player = player.toRoomPlayer();
        String gcTopic = gameCenterWatcher.getCenterTopic("fish");
        if (gcTopic == null) {
            respFailed(player, MessageId.G2C_GCEnterFishTableResp, "游戏还没开启");
            return;
        }
        LogicApp.mqClient.sendInter(topic, gcTopic, MqMsgId.l2gc_fish_enter_table, gc);
    }

    // gamecenter -> logic 玩家加入房间成功, 更新玩家状态
    private void handleEnterRoomResp(MqBeanMessage msg) {
        CommonGameStartNotice req = (CommonGameStartNotice) msg.getBean();
        GamePlayer player = playerManager.getPlayer(req.userId);
        if (player == null) {
            // 玩家可能已经掉线，缓存被清除
            logger.warn("handleEnterRoomResp failed, player not found, userId: {}", req.userId);
            return;
        }
        player.setGame(req.game);
        player.setCenterTopic(req.center);
        player.setRoomId(req.roomId);
        player.setTableId(req.tableId);
        player.setGame(req.game);
        player.setGameTopic(req.gameTopic);
    }

    private void handleEnterRoom(C2GPbRedirectMessage msg) {
//        String name = msg.getPb().getEnterRoom().getName();
//        String centerTopic = gameCenterWatcher.getCenterTopic(name);
//        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
//        XAssert.nonNull(player, msg.getSessionId());
//        GameCenterEnterRoom req = new GameCenterEnterRoom(name, msg.getPb().getEnterRoom().getId(), player.toRoomPlayer());
//        LogicApp.mqClient.sendInter(topic, centerTopic, MqMsgId.gamecenter_enter_room, req);
    }

    // 查询子游戏大厅
    private void handleGameCenterInfoQuery(C2GPbRedirectMessage msg) {
        String game = msg.getPb().getGameCenterInfoQuery().getGame();
        String gameTopic = gameCenterWatcher.getCenterTopic(game);
        if (gameTopic == null) {
            respToClient(msg, GateClientProto.G2CMessage.newBuilder()
                    .setMsgid(MessageId.G2C_GameCenterQueryResp)
                    .setResult(1)
                    .setWarning("抱歉，该游戏尚未开启")
                    .build());
            return;
        }
        // 请求转发到center
        LogicApp.mqClient.sendInter(topic, gameTopic, MqMsgId.gamecenter_info_query,
                ImmutableMap.of("game", game, "sid", msg.getSessionId(), "gate", msg.getFromGateTopic()));
    }

    //存款
    private void handleWithDepositMoney(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg);
        player.getUserBankModule().handleWithDepositMoney(msg);
        sendFlushData(player);
    }

    //取款
    private void handleDrawMoney(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg);
        player.getUserBankModule().handleWithDrawMoney(msg);
        //LogicApp.dbServer.applySupplyAndConsume1(this, msg,(m)-> LogicApp.dbServer.bankTransactionHandler.drawMoney(msg,player), LogicApp.dbServer.bankTransactionHandler::handleResult);
        sendFlushData(player);
    }

    //添加/登录用户银行
    private void addOrLoginUserBank(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg);
        player.getUserBankModule().addOrLoginUserBank(msg);
        sendFlushData(player);
    }

    //修改银行密码
    private void updateUserBankPwd(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg);
        player.getUserBankModule().updateBankPwd(msg);
    }

    //银行存取款记录
    private void handleBankAssetsLog(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg);
        player.getUserBankModule().queryBankAssetsLog(msg);
    }

    //用户删除消息
    private void deletUserMsg(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg);
        player.getUserMessageModule().deleteMsg(msg);

    }

    // 用户查询消息
    private void handleQueryMsg(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg);
        player.getUserMessageModule().handleQueryMsg(msg);
    }

    //查询背包
    private void handleQueryBackPack(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg);
        player.getBackPackModule().handleQueryBackPack(msg);

    }

    // 中间件内部消息
    private void handleBeanMessage(MqBeanMessage msg) {
        switch (msg.getMsgId()) {

        }
    }

    //玩家注册
    private void handleRegist(C2GPbRedirectMessage msg) {
        LogicApp.dbServer.applySupplyAndConsume1(this, msg, LogicApp.dbServer.registHandler::regist,
                this::handlerRegistResult);
    }

    private void handlerRegistResult(C2GPbRedirectMessage msg, Pair<Integer, String> result) {
        GateClientProto.G2CMessage.Builder g2cBuilder = GateClientProto.G2CMessage.newBuilder();
        GateClientProto.RegistResp.Builder regRespBuilder = GateClientProto.RegistResp.newBuilder();
        switch (result.getKey()) {
            case 1:
                g2cBuilder.setResult(1);
                regRespBuilder.setToken(result.getValue());
                LogicApp.dbServer.applySupplyAndSingleConsume1(this, msg, (m) -> LogicApp.dbServer.dbLoadHandler
                                .loadUser(msg.getFromGateTopic(), msg.getSessionId(), msg.getPb().getRegist().getUsername()),
                        this::handleLoadResult);
                break;
            case 2:
                g2cBuilder.setResult(2);
                g2cBuilder.setWarning("帐号已存在");
                break;
            case 3:
                g2cBuilder.setResult(3);
                g2cBuilder.setWarning("昵称已存在");
                break;
            case 4:
                g2cBuilder.setResult(2);
                g2cBuilder.setWarning("注册信息格式不正确");
                break;
            default:
                g2cBuilder.setResult(2);
                g2cBuilder.setWarning("ERROR");
        }
        respToClient(msg, g2cBuilder.setMsgid(MessageId.G2C_RegistResp).setRegistResp(regRespBuilder.build()).build());
    }

    //玩家登陆
    private void handleLogin(C2GPbRedirectMessage msg) {
    	GamePlayer player=null;
        String username = msg.getPb().getLogin().getUsername();
        String token = msg.getPb().getLogin().getToken();
        //TODO 测试
        if(!CheckUtils.checkUserName(username)&&StringUtils.isBlank(token)){
        	handleLoginQueryResult(msg,Pair.of(6, ""));
        	return;
        }
        if(CheckUtils.checkUserName(username)){
        	player=playerManager.getPlayerByName(username);
        }else if(StringUtils.isNotBlank(token)){
        	player=playerManager.getPlayerByToken(token);
        }
        if(player!=null){
            player.setGateTopic(msg.getFromGateTopic());
            player.setSessionId(msg.getSessionId());
            playerManager.add(player);
            GateClientProto.G2CMessage resp = GateClientProto.G2CMessage.newBuilder().setMsgid(MessageId.G2C_LoginResp)
                    .setResult(1)
                    .setLoginresp(GateClientProto.LoginResp.newBuilder().setToken(player.getToken()))
                    .build();
            LogicApp.mqClient.sendClient(player.getGateTopic(), player.getSessionId(), resp);
            sendFlushData(player);
    	}else{
    		LogicApp.dbServer.applySupplyAndConsume1(this, msg, LogicApp.dbServer.loginHandler::login,
                    this::handleLoginQueryResult);
    	}
    }

    private void handleLoginQueryResult(C2GPbRedirectMessage msg, Pair<Integer, String> result) {
        GateClientProto.G2CMessage.Builder g2cBuilder = GateClientProto.G2CMessage.newBuilder();
        GateClientProto.LoginResp.Builder loginRespBuilder = GateClientProto.LoginResp.newBuilder();
        switch (result.getKey()) {
            case -1:
                g2cBuilder.setResult(1);
                loginRespBuilder.setToken(result.getValue().split(",")[0]);
                LogicApp.dbServer.applySupplyAndSingleConsume1(this, msg, (m) -> LogicApp.dbServer.dbLoadHandler
                                .loadUser(msg.getFromGateTopic(), msg.getSessionId(), result.getValue().split(",")[1]),
                        this::handleLoadResult);
                break;
            case 1:
                g2cBuilder.setResult(1);
                loginRespBuilder.setToken(result.getValue());
                LogicApp.dbServer.applySupplyAndSingleConsume1(this, msg, (m) -> LogicApp.dbServer.dbLoadHandler
                                .loadUser(msg.getFromGateTopic(), msg.getSessionId(), msg.getPb().getLogin().getUsername()),
                        this::handleLoadResult);
                break;
            case 2:
                g2cBuilder.setResult(2);
                g2cBuilder.setWarning("密码不正确");
                break;
            case 3:
                g2cBuilder.setResult(3);
                g2cBuilder.setWarning("密码错误次数超限，请在超限之后15分钟再试");
                break;
            case 4:
                g2cBuilder.setResult(4);
                g2cBuilder.setWarning("帐号不存在");
                break;
            case 0:
                g2cBuilder.setResult(0);
                g2cBuilder.setWarning("请登录");
            default:
                g2cBuilder.setResult(result.getKey());
                g2cBuilder.setWarning("ERROR");
        }
        // 登陆应答
        respToClient(msg, g2cBuilder.setMsgid(MessageId.G2C_LoginResp).setLoginresp(loginRespBuilder.build()).build());
    }

    // 手机验证码
    private void handleCaptcha(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        XAssert.nonNull(player, msg);
        LogicApp.assistServer.applySupplyAndConsume2(this, msg, player, LogicApp.assistServer::captcha,
                this::handleCaptchaResult);
    }

    private void handleCaptchaResult(C2GPbRedirectMessage msg, int result) {
        GateClientProto.G2CMessage.Builder g2cBuilder = GateClientProto.G2CMessage.newBuilder();
        switch (result) {
            case 1:
                g2cBuilder.setResult(1);
                break;
            case 0:
                g2cBuilder.setResult(0);
                g2cBuilder.setWarning("验证码不正确");
            default:
                g2cBuilder.setResult(-1);
                g2cBuilder.setWarning("ERROR");
        }
        respToClient(msg, g2cBuilder.setMsgid(MessageId.G2C_CaptchaResp).build());
    }

    // 玩家信息修改
    private void handleUserBaseInfo(C2GPbRedirectMessage msg) {
        GamePlayer player = playerManager.getPlayerBySessionId(msg.getSessionId());
        switch (msg.getPb().getChangeUserBaseInfoReq().getAction()) {
            case 0:
                LogicApp.dbServer.applySupplyAndConsume2(this, msg, player,
                        LogicApp.dbServer.userBaseInfoHandler::changePwd, this::handleUserBaseInfoResult);
                break;
            case 1:
                int result = LogicApp.assistServer.verifyCaptcha(String.valueOf(player.getUserId()), msg.getPb().getChangeUserBaseInfoReq().getCaptcha());
                if (result == 1) {
                    LogicApp.dbServer.applySupplyAndConsume2(this, msg, player, LogicApp.dbServer.userBaseInfoHandler::resetPwd,
                            this::handleUserBaseInfoResult);
                } else {
                    handleUserBaseInfoResult(msg, 6);
                }
                break;
            case 2:
                LogicApp.dbServer.applySupplyAndConsume2(this, msg, player,
                        LogicApp.dbServer.userBaseInfoHandler::changeIconOrNickname, this::handleUserBaseInfoResult);
                break;
            default:
                handleUserBaseInfoResult(msg, 4);
        }
    }

    private void handleUserBaseInfoResult(C2GPbRedirectMessage msg, int result) {
        GateClientProto.G2CMessage.Builder g2cBuilder = GateClientProto.G2CMessage.newBuilder();
        switch (result) {
            case 1:
                g2cBuilder.setResult(1);
                break;
            case 2:
                g2cBuilder.setResult(2);
                g2cBuilder.setWarning("昵称已存在");
                break;
            case 3:
                g2cBuilder.setResult(3);
                g2cBuilder.setWarning("密码不正确");
                break;
            case 4:
                g2cBuilder.setResult(4);
                g2cBuilder.setWarning("请求参数错误");
                break;
            case 0:
                g2cBuilder.setResult(0);
                g2cBuilder.setWarning("操作失败，请重试");
                break;
            case 5:
                g2cBuilder.setResult(5);
                g2cBuilder.setWarning("ERROR");
                break;
            case 6:
                g2cBuilder.setResult(6);
                g2cBuilder.setWarning("验证码不正确");
                break;
        }
        respToClient(msg, g2cBuilder.setMsgid(MessageId.G2C_ChangeUserBaseInfoResp).build());
    }

    //处理登录结果
    private void handleLoadResult(UserSessionMessage<GamePlayer> msg) {
        GamePlayer player = msg.getT();
        XAssert.isTrue(player != null, msg);
        // 设置3个上层参数
        player.setSessionId(msg.getSessionId());
        player.setGateTopic(msg.getFromGateTopic());
        player.setLogicTopic(topic);
        playerManager.add(player);
        sendFlushData(player);
    }

    private void sendFlushData(GamePlayer player) {
        GateClientProto.G2CMessage resp;
        GateClientProto.UserFlushData.Builder bu;
        bu = GateClientProto.UserFlushData.newBuilder().setUserId(player.getUserId())
                .setUserCode(player.getUserCode()).setUserBankGold(player.getUserBankGold())
                .setUserNickName(player.getUserNickName())
                .setPwd(player.getPwd()).setUserHorn(player.getUserHorn()).setUserIcon(player.getUserIcon())
                .setUserVipLevel(player.getUserVipLevel()).setUserLevel(player.getUserLevel())
                .setUserExp(player.getUserExp()).setUserBankGold(player.getUserBankGold())
                .setUserWalletGold(player.getUserWalletGold());
        if (player.getBankPwd() != null) {
            bu.setHasBankPwd(1);
        }else {
			bu.setHasBankPwd(0);
		}
        resp = GateClientProto.G2CMessage.newBuilder()
                .setFlushdata(bu)
                .setMsgid(MessageIdProto.MessageId.G2C_UserFlushData).build();
        respToClient(player.getGateTopic(), player.getSessionId(), resp);
    }

    private void respToClient(UserSessionMessage session, GateClientProto.G2CMessage msg) {
        respToClient(session.getFromGateTopic(), session.getSessionId(), msg);
    }

    private void respToClient(C2GPbRedirectMessage from, GateClientProto.G2CMessage msg) {
        respToClient(from.getFromGateTopic(), from.getSessionId(), msg);
    }

    private void respToClient(String fromGateTopic, long sid, GateClientProto.G2CMessage msg) {
        LogicApp.mqClient.sendClient(fromGateTopic, sid, msg);
    }

    private void respFailed(GamePlayer player, MessageId msgId, String fail) {
        LogicApp.mqClient.sendClient(player.getGateTopic(), player.getSessionId(),
                GateClientProto.G2CMessage.newBuilder()
                    .setMsgid(msgId)
                    .setWarning(fail)
                    .setResult(0)
                    .build());
    }

}
